/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2018年07月30日
*   描    述：
*   
================================================================*/


#include <iostream>

using namespace std;

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if( root == NULL || root == p || root == q )
            return root;

        TreeNode *left = lowestCommonAncestor(root->left, p, q);
        TreeNode *right = lowestCommonAncestor(root->right, p, q);
        /*
         *left != NULL && right != NULL说明p, q分别在root的左右节点，则root为p和q的最近公共祖先
         *left != NULL && right == NULL说明p，q在root的左节点，则left为p和q的最近公共祖先
         */
        
        if( left && right )
            return root;
        
        if( left )
            return left;

        return right;
    }
};
